package org.android.kumoh_ing;

import java.net.URL;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;

public class FeedListAdapter extends BaseAdapter {

	public static String TAG = "FeedListAdapter";

	private Context mContext;
	
	private ArrayList<FeedItem> mItems = new ArrayList<FeedItem>();

	private ArrayList<String> mList = new ArrayList<String>(); 
	
	public FeedListAdapter(Context context) {
		mContext = context;
	}

	public void setListItems(ArrayList<FeedItem> list) {
		mItems = list;
	}

	public void clear() {
		if (mItems != null) {
			mItems.clear();
		}
	}
	
	public ArrayList<String> getCheckedIds(){
		  mList.clear();

		 for(int i=0;i<getCount();i++){
		   if(mItems.get(i).getState()==true){
		    //////TODO
		    
		    mList.add(mItems.get(i).getId());
		   }
		  }
		 
		  return mList;
	}
	

	public void addItem(FeedItem aItem) {
		mItems.add(aItem);
	}

	public int getCount() {
		return mItems.size();
	}

	public Object getItem(int position) {
		return mItems.get(position);
	}

	public boolean areAllItemsSelectable() {
		return false;
	}

	public boolean isSelectable(int position) {
		return true;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		
		FeedItemView itemView;
		final int pos = position;
		if (convertView == null) {
			itemView = new FeedItemView(mContext);
			
		} else {
			itemView = (FeedItemView) convertView;			
		}
		
		try {
			FeedItem curItem = mItems.get(position);

			String name = curItem.getName();
			String pictureUrl = curItem.getPicture();
	
			itemView.setText(0, name);

			if (pictureUrl != null) {
				Bitmap curBitmap = BitmapFactory.decodeStream(new URL(pictureUrl).openStream());
				itemView.setIcon(curBitmap);
			} else {
				
				itemView.setIcon(facebookvalue.BasicPicture);
			}
			
			CheckBox mCheck = (CheckBox)convertView.findViewById(R.id.checkbtn);
			mCheck.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if(mItems.get(pos).getState()==true){
						mItems.get(pos).setState(false);
					}
					else{
						mItems.get(pos).setState(true);
					}
				}
			});
			mCheck.setChecked(mItems.get(pos).getState());
			
		} catch(Exception ex) {
			ex.printStackTrace();
		}

		return itemView;
	}

}
